import { ref, Ref, onMounted, onUnmounted } from 'vue'

interface FullScreenHooks {
  isFullScreen: Ref<boolean>;
  toggleFullScreen: () => void
}

interface FullScreenProps {
  esc ?: boolean,
  onEnter ?: () => void,
  onError ?: (e: any) => void,
  onExit ?: () => void
}

/**
 * @description 全屏hooks
 * @author jinzz
 * @param options { FullScreenProps } hooks初始化参数，包含esc退出、onEnter 全屏回调、onExit 取消全屏回调，onError 切换失败回调
 * @returns isFullScreen { Boolean } 是否全屏状态
 * @returns toggleFullScreen { () => void } 切换全屏
 * @example
 * import { useFullScreen } from '@hooks/useFullScreen'
 * const { isFullScreen, toggleFullScreen } = useFullScreen()
 * <svg-icon :icon-name="isFullScreen ? 'tuichuquanping' : 'fullscreen'" :size="22" @click.stop="toggleFullScreen" />
 */
export function useFullScreen( option : FullScreenProps = { esc: true }) :FullScreenHooks {
  const isFullScreen :Ref<boolean> = ref(false)

  const enterFullScreen = () => {
    try {
      document.documentElement.requestFullscreen()
      isFullScreen.value = true
      option.onEnter && option.onEnter()
    } catch (e) {
      option.onError && option.onError(e)
    }
  }

  const exitFullScreen = () => {
    try {
      document.exitFullscreen()
    isFullScreen.value = false
      option.onExit && option.onExit()
    } catch (e) {
      option.onError && option.onError(e)
    }
  }

  const toggleFullScreen = () => {
    if (isFullScreen.value) {
      exitFullScreen()
    } else {
      enterFullScreen()
    }
  }

  // 监听全屏状态改变事件
  const handleFullScreenChange = () => {
    isFullScreen.value = !!document.fullscreenElement
  }

  const handleEscKey = (event :KeyboardEvent) => {
    if (event.key === 'Escape') {
      exitFullScreen()
    }
  }

  onMounted(() => {
    document.addEventListener('fullscreenchange', handleFullScreenChange)
    option.esc && document.addEventListener('keydown', handleEscKey)
  })

  onUnmounted(() => {
    document.removeEventListener('fullscreenchange', handleFullScreenChange)
    option.esc && document.removeEventListener('keydown', handleEscKey)
  })

  return {
    isFullScreen,
    toggleFullScreen
  }
}